package com.example.zhihu.service.Imp;

import com.example.zhihu.mapper.ModularMapper;
import com.example.zhihu.pojo.Modular;
import com.example.zhihu.service.ModualService;
import com.example.zhihu.utils.PagedResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class ModualServiceImp implements ModualService  {

    @Autowired
    private ModularMapper modularMapper;

    @Autowired
    private Sid sid;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Modular addModual(Modular modular) {
        String id = sid.nextShort();
        modular.setId(id);
        modularMapper.insert(modular);
        return modular;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Modular updateModual(Modular modular) {
        Example example = new Example(Modular.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",modular.getId());
        modularMapper.updateByExampleSelective(modular,example);
        return modular;
    }

    @Override
    public PagedResult modualList(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Modular> list = modularMapper.selectAll();
        PageInfo<Modular> pageInfo = new PageInfo<>(list);
        PagedResult pagedResult = new PagedResult();
        pagedResult.setPage(page);
        pagedResult.setRecords(pageInfo.getTotal());
        pagedResult.setRows(list);
        pagedResult.setTotal(pageInfo.getPages());
        return pagedResult;
    }
}
